const ConvModel = require('../model/conv.model')
const NewsModel = require('../model/news.model')
const UserModel = require('../model/user.model')
const { verifyToken } = require("../utils/jwt");
const logger = require('../utils/log4js')
const { verifyParams } = require('../utils/utils')

module.exports = {
    /**
     * 获取会话列表
     */
    convList: async (req, res) => {
        let token = req.headers.token
        let { data } = verifyToken(token)
        const list = await ConvModel.find({
            crowd: {
                $in: [data._id]
            }
        }).populate('crowd')

        return res.json({
            code: 1,
            data: list
        })
    },
    /**
     * 获取会话信息列表
     * 根据 lastTime(用户最后一次查看消息的时间) 判断从哪里开始获取消息
     * - 获取 lastTime 以后的所有消息
     * - 不足20条时，补满20
     */
    convNews: async (req, res) => {
        let verify = verifyParams(req.body, [
            {
                key: 'convId',
                rule: [
                    { required: true },
                    { type: 'string' }
                ]
            },
            {
                key: 'lastTime',
                rule: [
                    { required: true }
                ]
            }
        ])
        if (verify) return res.json({ code: 0, msg: verify })

        try {
            let news = await NewsModel.find({
                // $lt:指定日期之前；$gt:指定日期之后；$gte:指定日期及之后；gte~lt:指定日期之间
                time: {
                    $gte: new Date(req.body['lastTime'])
                },
                convId: req.body.convId
            }).populate('sender', '-pwd').lean()
            // logger.info('news1', news)
            if (news.length < 20) {
                // 不足20条时，补满20
                let count = 20 - news.length
                const _news = await NewsModel.find({
                    time: {
                        $lt: new Date(req.body['lastTime'])
                    },
                    convId: req.body.convId
                }).populate('sender', '-pwd').limit(count).lean()
                // logger.info('_news', _news)
                if (_news.length > 0) {
                    news = news.concat(_news)
                }
            }
            // logger.info('news', news)
            return res.json({
                code: 1,
                data: news,
                msg: '获取成功'
            })
        } catch (e) {
            return res.json({
                code: 0,
                data: [],
                msg: e
            })
        }
    },
    /**
     * 创建会话
     */
    createConv: async (req, res) => {
        let verify = verifyParams(req.body, [
            {
                key: 'userId',
                rule: [
                    { required: true },
                    { type: 'array' }
                ]
            }
        ])
        if (verify) return res.json({ code: 0, msg: verify })

        let token = req.headers.token
        let { data } = verifyToken(token)
        let title = ''
        if (req.body.userId.length > 1) {
            // 群聊时设置默认群聊名称
            const users = await UserModel.find({
                _id: req.body.userId
            }, 'name').lean()
            title = users.map(user => user.name).join(',')
        }

        const conv = await new ConvModel({
            crowd: [...req.body.userId, data._id],
            title
        })
        await conv.save()
        return res.json({
            code: 1,
            msg: '操作成功',
            data: conv
        })
    },
    /**
     * 发送消息
     */
    sendMsg: async (req, res) => {
        let verify = verifyParams(req.body, [
            {
                key: 'text',
                rule: [
                    { required: true },
                    { type: 'string' }
                ]
            },
            {
                key: 'convId',
                rule: [
                    { required: true },
                    { type: 'string' }
                ]
            }
        ])
        if (verify) return res.json({ code: 0, msg: verify })

        let token = req.headers.token
        let { data } = verifyToken(token)
        let news = await new NewsModel({
            convId: req.body.convId,
            text: req.body.text,
            sender: data._id
        })
        await news.save()
        return res.json({
            code: 1,
            msg: '发送成功!',
            data: news
        })
    }
}